package com.seashop.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.seashop.constant.RedisConstant;
import com.seashop.redis.RedisZero;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author moredln
 * @desc 短信限制
 * @date 2020-10-30 13:48
 */
@Component
@Slf4j
public class SmsLimitUtils {

    @Autowired
    private RedisZero redisZero;

    /**
     * 发送验证码
     *
     * @return 1:间隔未超过一分钟，请一分钟之后重试！
     * 2:今天发送次数超过限制，请明天再试！
     * 3:可以发送
     */
    public JSONObject checkSmsLimit(String mobile) {
        JSONObject result = new JSONObject(3);
        JSONObject smsLimit = new JSONObject();
        if (redisZero.exists(mobile)) {
            String s = redisZero.get(mobile).toString();
            try {
                smsLimit = JSON.parseObject(s);
            } catch (Exception e) {
                smsLimit = new JSONObject();
            }
        }

        String value = redisZero.get(RedisConstant.SMS_LIMIT).toString();

        Integer limit = null;
        if (StringUtils.isNotBlank(value)) {
            limit = Integer.parseInt(value);
        }
        if (null == limit || limit <= 0) {
            result.put("status", 2);
            return result;
        }
        if (null != smsLimit && smsLimit.size() > 0) {
            Integer number = smsLimit.getInteger("number");
            // 间隔未超过一分钟，请一分钟之后重试！;
            if (null != smsLimit.getDate("date") && DateUtil.getBetweenSecond(smsLimit.getDate("date"), new Date()) < 60) {
                log.info("间隔未超过一分钟，请一分钟之后重试！");
                result.put("status", 1);
                return result;
            }
            // 今天发送次数超过限制，请明天再试！;
            if (number >= limit) {
                log.info("今天发送次数超过限制，请明天再试！");
                result.put("status", 2);
                return result;
            }
            smsLimit.put("number", number + 1);
        } else {
            smsLimit.put("number", 1);
        }
        Date date = new Date();
        smsLimit.put("date", cn.hutool.core.date.DateUtil.format(date, "yyyy-MM-dd HH:mm:ss"));
        Date endDate = cn.hutool.core.date.DateUtil.endOfDay(new Date());
        Long time = endDate.getTime();
        Long newDate = date.getTime();
        redisZero.setex(mobile, smsLimit.toJSONString(), new Long((time - newDate) / 1000).intValue(), TimeUnit.SECONDS);
        result.put("currentNumber", smsLimit.getInteger("number"));
        result.put("remainNumber", limit - smsLimit.getInteger("number"));
        result.put("status", 3);
        return result;
    }

}
